//
//  NoticeViewController.m
//  FingerUniversity
//
//  Created by vantle on 16/3/10.
//  Copyright © 2016年 vantle. All rights reserved.
//

#import "NoticeViewController.h"
#import "NoticeCell.h"
#import "UIColor+hexColor.h"
#import "AFNetworking.h"
#import "MyMD5.h"
#import "SearchResultViewController.h"
#import "NoticeDetailViewController.h"
#import "NoticeModel.h"
#import "MTLJSONAdapter.h"
#import "MJRefresh.h"
#import "MobClick.h"
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
@interface NoticeViewController ()

@end

@implementation NoticeViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"NoticeViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"NoticeViewController"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor=[UIColor whiteColor];
    self.notice=2012;
    temp=1;
    pageNewNotice=1;
    UIImageView*bg=[[UIImageView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64)];
    bg.image=[UIImage imageNamed:@"bg"];
    [self.view addSubview:bg];
    
    UIImageView*barImage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 20, ScreenWidth, 44)];
    barImage.userInteractionEnabled=YES;
    barImage.backgroundColor=[UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1];
    [self.view addSubview:barImage];
    
    UIButton*backButton=[UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame=CGRectMake(0, 0, 100, 44);
    [backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [barImage addSubview:backButton];
    
    UIImageView*backImage=[[UIImageView alloc]initWithFrame:CGRectMake(5, 12, 5, 20)];
    backImage.image=[UIImage imageNamed:@"back_arrowleft"];
    [barImage addSubview:backImage];
    
    _logoImage=[[UIImageView alloc]initWithFrame:CGRectMake(backImage.frame.origin.x+backImage.frame.size.width+3, 6, 32, 32)];
    _logoImage.layer.cornerRadius=3;
    _logoImage.clipsToBounds=YES;
    _logoImage.image=[UIImage imageNamed:@"app-logo-80"];
    [barImage addSubview:_logoImage];
    
    _noticeLabel=[[UILabel alloc]initWithFrame:CGRectMake(_logoImage.frame.origin.x+_logoImage.frame.size.width+5, 10, 100, 25)];
    _noticeLabel.text=@"校园公告";
    [barImage addSubview:_noticeLabel];
    
    _searchButton=[UIButton buttonWithType:UIButtonTypeCustom];
    _searchButton.center=CGPointMake(ScreenWidth-30, barImage.center.y-20);
    _searchButton.bounds=CGRectMake(0, 0, 25, 25);
    [_searchButton setBackgroundImage:[UIImage imageNamed:@"abc_ic_search_api_mtrl_alpha"] forState:UIControlStateNormal];
    [_searchButton addTarget:self action:@selector(searchButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [barImage addSubview:_searchButton];
    
    
    _searchImage=[[UIImageView alloc]initWithFrame:CGRectMake(_logoImage.frame.origin.x+_logoImage.frame.size.width+10, _logoImage.frame.origin.y+26, 20, 20)];
    _searchImage.image=[UIImage imageNamed:@"abc_ic_search_api_mtrl_alpha"];
    _searchImage.hidden=YES;
    [self.view addSubview:_searchImage];
    
    _searchLabel=[[UILabel alloc]initWithFrame:CGRectMake(_searchImage.frame.origin.x+_searchImage.frame.size.width+5, _searchImage.frame.origin.y, 100, 25)];
    _searchLabel.text=@"搜索公告";
    _searchLabel.hidden=YES;
    _searchLabel.textColor=[UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:0.9];
    _searchLabel.font=[UIFont systemFontOfSize:19];
    [self.view addSubview:_searchLabel];
    
    _searchTextField =[[UITextField alloc]initWithFrame:CGRectMake(_logoImage.frame.origin.x+_logoImage.frame.size.width+10, _logoImage.frame.origin.y+20, ScreenWidth-_logoImage.frame.origin.x-_logoImage.frame.size.width-_searchButton.frame.size.width-20, 30)];
    _searchTextField.enabled=NO;
    _searchTextField.hidden=YES;
    _searchTextField.delegate=self;
    [self.view addSubview:_searchTextField];
    
    _lineView=[[UIImageView alloc]initWithFrame:CGRectMake(_searchTextField.frame.origin.x, _searchTextField.frame.origin.y+_searchTextField.frame.size.height, _searchTextField.frame.size.width+30, 1)];
    _lineView.hidden=YES;
    _lineView.backgroundColor=[UIColor blueColor];
    [self.view addSubview:_lineView];
    
    _resultButtonImage=[[UIImageView alloc]init];
    _resultButtonImage.center=CGPointMake(ScreenWidth-25,_searchImage.center.y );
    _resultButtonImage.bounds=CGRectMake(0, 0, 10, 15);
    _resultButtonImage.image=[UIImage imageNamed:@"abc_ic_go_search_api_mtrl_alpha"];
    _resultButtonImage.hidden=YES;
    [self.view addSubview:_resultButtonImage];
    
    _resuleButton=[UIButton buttonWithType:UIButtonTypeCustom];
    _resuleButton.center=CGPointMake(ScreenWidth-25,_searchImage.center.y );
    _resuleButton.bounds=CGRectMake(0, 0, 40, 44);
    _resuleButton.hidden=YES;
    [_resuleButton addTarget:self action:@selector(resultButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_resuleButton];
    
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-140)];
    _tableView.dataSource=self;
    _tableView.delegate=self;
    _tableView.rowHeight=60;
    _tableView.separatorColor=[UIColor whiteColor];
    _tableView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_tableView];
    
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    
    UIImageView*boardView=[[UIImageView alloc]init];
    boardView.center=CGPointMake(self.view.center.x, ScreenHeight-25);
    boardView.bounds=CGRectMake(0, 0, ScreenWidth-20, 50);
    boardView.image=[UIImage imageNamed:@"board"];
    [self.view addSubview:boardView];
    
    NSArray*buttonImageArray=@[@"最新公告",@"通知",@"校发文件",@"-校办文件",@"工部文件"];
    _buttonTitleArray=@[@"最新消息",@"学习新知",@"教学新知",@"活动公告",@"机构公告"];
    
    for (int i=0; i<5; i++) {
        UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
        button.tag=1+i;
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        if (i==0) {
            button.backgroundColor=[UIColor hexFloatColor:@"00DDFF"];
        }
        [button setExclusiveTouch:YES];
        [self.view addSubview:button];
        
        
        
        UILabel*buttonTitleLabel=[[UILabel alloc]init];
        
        buttonTitleLabel.bounds=CGRectMake(0, 0, 100, 20);
        buttonTitleLabel.textAlignment=1;
        buttonTitleLabel.text=_buttonTitleArray[i];
        
        
        if (ScreenWidth==414) {
            buttonTitleLabel.font=[UIFont systemFontOfSize:15];
            button.frame=CGRectMake(20+(ScreenWidth/5-8)*i, ScreenHeight-80, ScreenWidth/5-8, ScreenWidth/5-5);
        }
        else
        {
            buttonTitleLabel.font=[UIFont systemFontOfSize:13];
            button.frame=CGRectMake(20+(ScreenWidth/5-8)*i, ScreenHeight-80, ScreenWidth/5-8, ScreenWidth/5);
        }
        buttonTitleLabel.center=CGPointMake(button.center.x, button.center.y+25);
        [self.view addSubview:buttonTitleLabel];
        
        UIImageView*buttonImage=[[UIImageView alloc]init];
        buttonImage.center=CGPointMake(button.center.x, button.center.y-8);
        buttonImage.bounds=CGRectMake(0, 0, 40, 40);
        buttonImage.image=[UIImage imageNamed:buttonImageArray[i]];
        [self.view addSubview:buttonImage];
    }
    
    _listArray=[[NSMutableArray alloc]init];
    _newNoticeArray=[[NSMutableArray alloc]initWithCapacity:0];
    _sortNewNoticeArray=[[NSMutableArray alloc]initWithCapacity:0];
    
    
    [self getNewNotice];
    
    
}

#pragma mark 开始进入刷新状态
-(void)headerRereshing
{
    pageNewNotice = 1;
    
    if (temp==1) {
        
        [_newNoticeArray removeAllObjects];
        [self getNewNotice];
    }
    else
    {
        [self getNoticeInfo];
    }
    [_tableView headerEndRefreshing];
}
-(void)footerRereshing
{
    pageNewNotice += 1;
    if (temp==1) {
        [_newNoticeArray removeAllObjects];
        [self getNewNotice];
    }
    else
    {
        [self getNoticeInfo];
        
    }
    [_tableView footerEndRefreshing];
}



-(void)getNewNotice
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString*userId=[userDefaults objectForKey:@"userId"];
    NSString*flag=[userDefaults objectForKey:@"flag"];
    
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes =[manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    NSDictionary*params=@{@"userId":userId,@"flag":flag,@"start":@"0",@"end":[NSString stringWithFormat:@"%d",pageNewNotice*12],@"title":@"",@"classify":@""};
    
    [manager POST:@"http://120.76.79.85:9080/mzdx/service/noticeList.action" parameters:params success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData*responseData=responseObject;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData
                                                            options:NSJSONReadingMutableContainers
                                                              error:nil];
        NSLog(@"==========%@",dic);
        NSArray*noticeArray=[dic objectForKey:@"notices"];
        
        if ([noticeArray isKindOfClass:[NSArray class]]) {
            for (NSDictionary*tempDic in noticeArray) {
                NSError *error = nil;
                NoticeModel*noticeModel=[[NoticeModel alloc]init];
                noticeModel=[MTLJSONAdapter modelOfClass:[NoticeModel class] fromJSONDictionary:tempDic error:&error];
                if (error==nil) {
                    [_newNoticeArray addObject:noticeModel];
                    
                }
                
            }
            [self sortedArray:_newNoticeArray];
        }
        
    } failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];
}
-(void)sortedArray:(NSMutableArray*)arr
{
    
    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createTime"
                                                 ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    
    _sortNewNoticeArray =[arr sortedArrayUsingDescriptors:sortDescriptors];
    
    _listArray = [[_sortNewNoticeArray reverseObjectEnumerator] allObjects];
    NSLog(@"--------🐑%@",_listArray);
    if ((ScreenHeight-64)/60>_listArray.count) {
        _tableView.bounces=NO;
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, _listArray.count*60)];
        NSLog(@"少");
    }
    else
    {
        _tableView.bounces=YES;
        _tableView.frame=CGRectMake(0, 64, ScreenWidth, ScreenHeight-140);
        NSLog(@"多");
    }
    
    [_tableView reloadData];
    
    
}
-(void)getNoticeInfo
{
    [_tableView reloadData];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString*userId=[userDefaults objectForKey:@"userId"];
    NSString*flag=[userDefaults objectForKey:@"flag"];

    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes =[manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    NSDictionary*params=@{@"userId":userId,@"flag":flag,@"start":@"0",@"end":[NSString stringWithFormat:@"%d",pageNewNotice*12],@"title":@"",@"classify":[NSString stringWithFormat:@"%d",temp-1]};
    
    [manager POST:@"http://120.76.79.85:9080/mzdx/service/noticeList.action" parameters:params success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData*responseData=responseObject;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData
                                                            options:NSJSONReadingMutableContainers
                                                              error:nil];
        NSArray*noticeArray=[dic objectForKey:@"notices"];
        [_listArray removeAllObjects];
        if ([noticeArray isKindOfClass:[NSArray class]]) {
            for (NSDictionary*tempDic in noticeArray) {
                NSError *error = nil;
                NoticeModel*noticeModel=[[NoticeModel alloc]init];
                noticeModel=[MTLJSONAdapter modelOfClass:[NoticeModel class] fromJSONDictionary:tempDic error:&error];
                if (error==nil) {
                    [_listArray addObject:noticeModel];
                }
                
            }
            [_tableView reloadData];
            if ((ScreenHeight-64)/60>_listArray.count) {
                _tableView.bounces=NO;
                _tableView.frame=CGRectMake(0, 64, ScreenWidth, _listArray.count*60);
            }
            else
            {
                _tableView.frame=CGRectMake(0, 64, ScreenWidth, ScreenHeight-140);
                _tableView.bounces=YES;
            }
        }
        

    } failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];

}

-(void)buttonClick:(UIButton*)sender
{
    pageNewNotice=1;
    UIButton*button=(UIButton*)[self.view viewWithTag:temp];
    button.backgroundColor=[UIColor clearColor];
    sender.backgroundColor=[UIColor hexFloatColor:@"00DDFF"];
    temp=(int)sender.tag;
    if (sender.tag==1) {
        [_newNoticeArray removeAllObjects];
        [self getNewNotice];
        
    }
    else
    {
        
        [self getNoticeInfo];
    }
    NSLog(@"🐶＝＝%d",(int)sender.tag);
    
    
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString*cellIndentifier=@"cell";
    NoticeCell*cell=[tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell==nil) {
        cell=[[NoticeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.titleLabel.text=[_listArray[indexPath.row] title];
    cell.timeLbel.text=[_listArray[indexPath.row] createTime];
    cell.backgroundColor=[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:0.5];
    NSString*classify=[_listArray[indexPath.row] classify];
    if ([classify isEqualToString:@"1"]) {
        cell.myImage.image=[UIImage imageNamed:@"通知"];
    }
   else if ([classify isEqualToString:@"2"]) {
        cell.myImage.image=[UIImage imageNamed:@"校发文件"];
    }
   else if ([classify isEqualToString:@"3"]) {
       cell.myImage.image=[UIImage imageNamed:@"-校办文件"];
   }
    else
    {
        cell.myImage.image=[UIImage imageNamed:@"工部文件"];
    }
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NoticeDetailViewController*noticeDetailVC=[[NoticeDetailViewController alloc]init];
    NoticeModel*model=_listArray[indexPath.row];
    self.noticeIdChuan=model.noticeId;
    noticeDetailVC.noticeIdQu=self.noticeIdChuan;
    [self.navigationController pushViewController:noticeDetailVC animated:YES];
}
-(void)searchButtonClick:(UIButton*)sender
{
    _noticeLabel.hidden=YES;
    sender.hidden=YES;
    _searchTextField.enabled=YES;
    _searchTextField.hidden=NO;
    _searchImage.hidden=NO;
    _searchLabel.hidden=NO;
    _lineView.hidden=NO;
    _resuleButton.hidden=NO;
    _resultButtonImage.hidden=NO;
    
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    _searchImage.hidden=YES;
    _searchLabel.hidden=YES;
    
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}
-(void)resultButtonClick
{
    if (_searchTextField.text.length!=0) {
        SearchResultViewController*searchResultVC=[[SearchResultViewController alloc]init];
        self.searchText=_searchTextField.text;
//        searchResultVC.viewTag=self.notice;
        searchResultVC.result=self.searchText;
        [self.navigationController pushViewController:searchResultVC animated:YES];
    }
    
}
-(void)backButtonClick
{
    if (_searchTextField.text.length!=0) {
        _searchTextField.enabled=NO;
        _searchTextField.text=nil;
        _searchImage.hidden=YES;
       
        _searchLabel.hidden=YES;
        _searchButton.hidden=NO;
        _lineView.hidden=YES;
        _noticeLabel.hidden=NO;
        _resuleButton.hidden=YES;
        _resultButtonImage.hidden=YES;
    }
    else
    {
        [self.view endEditing:YES];
        if (_searchImage.hidden==NO) {
            _searchTextField.enabled=NO;
            _searchImage.hidden=YES;
            _searchLabel.hidden=YES;
            _searchButton.hidden=NO;
            _lineView.hidden=YES;
            _noticeLabel.hidden=NO;
            _resuleButton.hidden=YES;
            _resultButtonImage.hidden=YES;
        }
        else
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
}
-(void)viewDidLayoutSubviews
{
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
